package cn.admin.remoting.impl;

import cn.admin.remoting.RequestProcessor;
import cn.admin.remoting.locale.LogResources;
import cn.admin.remoting.util.LoggerInit;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

final class ProcessorUtil {

    private volatile ConcurrentHashMap<Class<?>, RequestProcessor<?>> processors;

    ProcessorUtil() {
        this(null);
    }

    private ProcessorUtil(Map<Class<?>,RequestProcessor<?>> processors) {
        this.processors = new ConcurrentHashMap<>();
        if (processors != null) {
            for (RequestProcessor<?> p : processors.values()) {
                this.registerProcessor(p);
            }
        }
    }

    void registerProcessor(RequestProcessor<?> processor) {

        if (processor.getExecutor() != processor.getExecutor()) {
            LoggerInit.LOGGER.error(LogResources.getLog(LogResources.INCORRECT_IMPL_REQUESTPROCESSOR,
                    processor), new Exception());
        } else {
            if (this.processors.putIfAbsent(processor.interest(),processor) != null) {
                LoggerInit.LOGGER.warn("不能重复注册Processor[" + processor.interest() + ", " + processor + "].",
                        new Exception());
            }
        }

    }

    @SuppressWarnings("unchecked")
    <T> RequestProcessor<T> removeProcessor(Class<T> appRequestClazz) {
        return (RequestProcessor<T>) this.processors.remove(appRequestClazz);
    }

    void updateProcessors(Map<Class<?>, RequestProcessor<?>> newProcessors) {
        this.processors = new ProcessorUtil(newProcessors).processors;
    }

    Map<Class<?>,RequestProcessor<?>> getProcessors() {
        return this.processors;
    }

    @SuppressWarnings("unchecked")
    <T> RequestProcessor<T> findProcessor(Class<T> appRequestClazz) {
        return (RequestProcessor<T>) this.processors.get(appRequestClazz);
    }

}
